package com.ylb.rent.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneId;

import java.time.temporal.ChronoUnit;
import java.util.Date;


/**
 * @AUTHOR:游李滨
 * @DATE:2023/6/27 22:52
 */

@Component
public class TokenUtil {

    @Value("${token.secret}")
    private String secret="adasf";

    @Value("${token.expire}")
    private int expire=1;

    private ChronoUnit chronoUnit=ChronoUnit.SECONDS;

    public String generateToken(long userId){

        JWTCreator.Builder builder = JWT.create();
        //设置过期时间
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime plus = now.plus(expire, chronoUnit);
        long expire =Date.from( plus.atZone(ZoneId.systemDefault()).toInstant()).getTime();
        builder.withExpiresAt(new Date(expire)).withClaim("id",userId);
        return builder.sign(Algorithm.HMAC256(secret));
    }
    public long verify(String token) throws Exception{
        DecodedJWT verify = JWT.require(Algorithm.HMAC256(secret)).build().verify(token);
        Claim id = verify.getClaim("id");
        return id.asLong();

    }
    public long getUserId(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return (long) authentication.getPrincipal();
    }


}
